import { App, createApp, onUnmounted, ref } from "vue";
import FModal from './modal.component';

export interface ModalOptions {
    class?: string;
    title?: string;
    width?: number;
    showButtons?: boolean;
    showHeader?: boolean;
    content?: { render(): JSX.Element };
    render?(app: App): JSX.Element;
    acceptCallback?(): void;
    rejectCallback?(): void;
}

function getContentRender(props: ModalOptions) {
    if (props.content && props.content.render) {
        return props.content.render;
    }
    if (props.render && typeof props.render === 'function') {
        return props.render;
    }
}

function createModalInstance(options: ModalOptions): App {
    const container = document.createElement('div');
    container.style.display = 'contents';
    const app: App = createApp({
        setup() {
            onUnmounted(() => {
                document.body.removeChild(container);
            });
            const customClass = ref(options.class || '');
            const showButtons = ref(!!options.showButtons);
            const showHeader = ref(!!options.showHeader);
            const showModal = ref(true);
            const modalTitle = ref(options.title || '');
            const acceptCallback = options.acceptCallback || (() => { });
            const rejectCallback = options.rejectCallback || (() => { });
            const contentRender = getContentRender(options);
            return () => (
                <FModal
                    class={customClass.value}
                    v-model={showModal.value}
                    title={modalTitle.value}
                    width={options.width}
                    show-header={showHeader.value}
                    show-buttons={showButtons.value}
                    onAccept={acceptCallback}
                    onCancel={rejectCallback}
                >
                    {contentRender && contentRender(app)}
                </FModal>
            );
        }
    });
    document.body.appendChild(container);
    app.mount(container);
    return app;
}

export default class ModalService {

    static show(options: ModalOptions): App {
        const modalOptions = Object.assign({
            title: '',
            showButtons: true,
            showHeader: true
        }, options);
        return createModalInstance(modalOptions);
    }
}
